# define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

 struct ListNode {
    int val;
    struct ListNode* next;
    
};


struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if (list1 == NULL)
    {
        return list2;
    }
    else if (list2 == NULL)
    {
        return list1;
    }
    struct ListNode* prev1 = list1;
    struct ListNode* prev2 = list2;
    struct ListNode* head = NULL;
    struct ListNode* tail = head;
    while (prev1 && prev2)
    {
        if (prev1->val <= prev2->val)
        {
            if (head == NULL)
            {
                head = tail = prev1;
            }
            else
            {
                tail->next = prev1;
                tail = tail->next;
            }
            prev1 = prev1->next;
        }
        else
        {
            if (head == NULL)
            {
                head = tail = prev2;
            }
            else
            {
                tail->next = prev2;
                tail = tail->next;
            }
            prev2 = prev2->next;
        }
    }
    if (prev1)
    {
        tail->next = prev1;
    }
    if (prev2)
    {
        tail->next = prev2;
    }
    return head;
}